package com.bjsxt.shop.back.springmvc.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.shop.common.controller.BaseController;
import com.bjsxt.shop.common.util.ConstatFinalUtil;
import com.bjsxt.shop.common.util.PageInfoUtil;
import com.bjsxt.shop.goods.pojo.AGoods;
import com.bjsxt.shop.goods.pojo.AGoodsBrand;
import com.bjsxt.shop.goods.pojo.AGoodsBrandEnum;
import com.bjsxt.shop.goods.pojo.AGoodsCate;
import com.bjsxt.shop.goods.service.IGoodsService;
import com.bjsxt.shop.users.pojo.AAdmins;

/**
 * URL规划,拦截器拦截
 * 
 * @author WYN
 *
 */
@Controller
@RequestMapping("/back/goods/")
public class GoodsBackController extends BaseController {
	@Resource
	private IGoodsService goodsService;

	/**
	 * 品牌列表
	 * 
	 * @return
	 */
	@RequestMapping("/brandList")
	public String brandList() {
		ConstatFinalUtil.SYS_LOGGER.info("---brandList--");
		return "/back/goods/brandList";
	}

	/**
	 * 品牌列表--返回JSON数据
	 * 
	 * { "total":28, "rows": [ {"productid":"AV-CB-01","productname":
	 * "Amazon Parrot","unitcost":92.00,"status":"P","listprice":63.50,"attr1":
	 * "Adult Male","itemid":"EST-18"} ]}
	 * 
	 * 
	 * @return
	 */
	@RequestMapping(value = "/brandListJSON", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String brandListJSON(String page, String rows) {
		ConstatFinalUtil.SYS_LOGGER.info("---brandListJSON--");
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(page, rows);
		Map<String, Object> condMap = new HashMap<String, Object>();
		/* 查询列表 */
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsBrandService(pageInfoUtil, condMap);
		/* 数据 */
		List<AGoodsBrand> brandList = (List<AGoodsBrand>) resultMap.get("list");
		int totalRecord = Integer.valueOf(resultMap.get("totalRecord") + "");

		/* 拼装数据,json */
		JSONObject resultJSON = new JSONObject();
		resultJSON.put("total", totalRecord);

		/* 数据 */
		JSONArray dataArr = new JSONArray();
		int count = 1;
		for (Iterator iterator = brandList.iterator(); iterator.hasNext();) {
			AGoodsBrand brand = (AGoodsBrand) iterator.next();
			JSONObject brandJSON = brand.toJSON();
			brandJSON.put("count", count);

			/* brand对象变成JSON */
			dataArr.add(brandJSON);
			count++;
		}
		resultJSON.put("rows", dataArr);
		return resultJSON.toJSONString();
	
	}

	/**
	 * 品牌添加
	 * 
	 * @return
	 */
	@RequestMapping("/brandInsert")
	public String brandInsert() {
		ConstatFinalUtil.SYS_LOGGER.info("---brandInsert--");
		return "/back/goods/brandInsert";
	}

	/**
	 * 品牌添加提交
	 * 在品牌提交的時候是json格式
	 * @return 返回JSON { "code":"0", "info":"", }
	 */
	@RequestMapping(value = "/brandInsertSubmit", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String brandInsertSubmit(String pubtimeStr, AGoodsBrand goodsBrand, MultipartFile file,HttpSession session) {
		ConstatFinalUtil.SYS_LOGGER.info("---brandInsertSubmit--");
		JSONObject resultJSON = new JSONObject();
		//文件上传
		ConstatFinalUtil.SYS_LOGGER.info("---file:{}-",file);
		//二进制的形式读取文件
		if(file!=null&&!"".equalsIgnoreCase(file.getOriginalFilename())){
			String originalFilename=file.getOriginalFilename();
			String fileName="";
			//上传文件到ftp中
			/**
			 * 上传路径的拼装
			 * 格式：uploadfile/brand/2017-06-28/uuid.jpg
			 */
			try {
				String relaPath=ConstatFinalUtil.CONFIG_JSON.getString("relaPath");
				relaPath += "/brand/" + this.dateFormatUtil.dateStr(new Date()) + "/";
				fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
				boolean flag=this.ftpUtil.uploadFile(fileName, relaPath, file.getInputStream());
				if(flag)
				{
					/* 上传文件成功
					 * 存储数据库: */
					goodsBrand.setLogoPath(relaPath + fileName);
				}
			} catch (IOException e) {
				ConstatFinalUtil.SYS_LOGGER.error("上传文件失败了,文件名:{}",fileName,e);
			}
			
		}
		/* 自己来转换时间,就不用转换器了 */
		goodsBrand.setPubTime(this.dateFormatUtil.strDateTime(pubtimeStr));

		/* 把页面上没有赋值的属性进行赋值 */
		
		AAdmins adminsSess = (AAdmins) session.getAttribute("admins");
		goodsBrand.setAdminsId(adminsSess.getId());
		goodsBrand.setCreateTime(new Date());
		goodsBrand.setUpdateTime(new Date());
		/* 保存数据 */
		resultJSON = this.goodsService.saveOneGoodsBrandService(goodsBrand);
		return resultJSON.toJSONString();
	}
	
	//商品模块打开商品模块表
	@RequestMapping("/goodsList")
	public String goodsList()
	{
		ConstatFinalUtil.SYS_LOGGER.info("==goodsList===");
		return "/back/goods/goodsList" ; 
	}
	
	@RequestMapping(value ="/goodsListJSON",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String goodsListJSON(HttpServletRequest request,String page,String rows,String keyword , String status,String st,String ed)
	{
		ConstatFinalUtil.SYS_LOGGER.info("==goodsList===");
		/* 处理get方式的乱码 */
		try
		{
			keyword = new String(keyword.getBytes("ISO8859-1"), "UTF-8");
		} catch (Exception e)
		{
		}
		/*
		 * 分页信息
		 */
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(page, rows);
		
		/* 搜索条件 */
		if(status == null)
		{
			status = "" ; 
		}
		if(st == null)
		{
			st = "" ; 
		}
		if(ed == null)
		{
			ed = "" ; 
		}
		
		Date stDate = null ; 
		Date edDate = null ; 
		if(!"".equalsIgnoreCase(st) && !"".equalsIgnoreCase(ed))
		{
			/* 从字符中变成日期时间对象 */
			stDate = this.dateFormatUtil.strDateTime(st);
			edDate = this.dateFormatUtil.strDateTime(ed);
		}
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("keyword", keyword);
		
		if(!"".equalsIgnoreCase(status))
		{
			condMap.put("status", status);
		}
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		
		/* 查询列表 */
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsService(pageInfoUtil, condMap);
		/* 数据 */
		List<AGoods> goodsList = (List<AGoods>) resultMap.get("list");
		int totalRecord = Integer.valueOf(resultMap.get("totalRecord") + "");
		
		/* 拼装数据,json */
		JSONObject resultJSON = new JSONObject() ;
		resultJSON.put("total", totalRecord);
		
		/* 数据 */
		JSONArray dataArr = new JSONArray() ; 
		for (Iterator iterator = goodsList.iterator(); iterator.hasNext();)
		{
			AGoods goodsTemp = (AGoods) iterator.next();
			JSONObject brandJSON = goodsTemp.toJSON();
			
			/* brand对象变成JSON */
			dataArr.add(brandJSON);
		}
		resultJSON.put("rows", dataArr);
		return resultJSON.toJSONString() ;
	}
	
	/**
	 * 打开商品添加页面
	 */
	@RequestMapping("/goodsInsert")
	public String goodsInsert(Model model){
		//获取商品分类下拉菜单
		Map<String, Object> condMap=new HashMap<String,Object>();
		//每次查询的前提先行清除
		condMap.clear();
		condMap.put("status", AGoodsBrandEnum.STATUS_ENABLE.getStatus());
		Map<String, Object> resultMap = this.goodsService.findCondListGoodsBrandService(null, condMap);
		List<AGoodsBrand> brandList = (List<AGoodsBrand>) resultMap.get("list");
		//设置到作用域当中
		model.addAttribute("brandList", brandList);
		List<AGoodsCate> goodsCateTreeList = this.goodsService.findTreeListCateService();
		//设置到作用域当中
		model.addAttribute("goodsCateTreeList", goodsCateTreeList);
		
		return "/back/goods/goodsInsert";
		
	}
	/**
	 * 商品添加成功请求页面
	 */
	@ResponseBody
	@RequestMapping(value="/goodsInsertSubmit.htm",produces="text/html;charset=UTF-8")
	public String goodsInsertSubmit(AGoods goods,String pubtimeStr,HttpSession session,HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("--goodsInsert--");
		JSONObject resultJSON = new JSONObject() ; 
		/**
		 * @author WYN
		 * 获取前台页面填写的信息
		 * 一分类标签为来获取所选的分来标签的下面的值
		 */ 
		Map<String, Object> condMap = new HashMap<String, Object>();
		//根据商品的id来进行查询值
		condMap.put("id", goods.getCateId());
		//查询一条商品分类
		AGoodsCate goodsCate=this.goodsService.findOneGoodsCateService(condMap);
		//循环json对象
		/**获取到的值的样式
		 * [
				{
					"name": "功能",
					"keys": [
					{
						"name":"制冷类型",
						"values":"冷暖"
					}
				}
			]
		 */
		JSONArray specArr = goodsCate.getSpecArr(); 
		for (Iterator iterator = specArr.iterator(); iterator.hasNext();) {
			JSONObject jsonTemp1 = (JSONObject) iterator.next();
			JSONArray keysArr = (JSONArray) jsonTemp1.get("keys");
			for (Iterator iterator2 = keysArr.iterator(); iterator2.hasNext();) {
				JSONObject jsonKeyTemp2 = (JSONObject) iterator2.next();
				//获取到的values值进行拼接
				String keyParam = "spec_" + jsonTemp1.get("name") + "_" + jsonKeyTemp2.get("name");
				//keys值是不确定的
				String value = request.getParameter(keyParam);
				jsonKeyTemp2.put("values", value);
			}
		}
		goods.setSpec(specArr.toJSONString());
		AAdmins adminsSess=(AAdmins) session.getAttribute("admins");
		goods.setPubTime(this.dateFormatUtil.strDateTime(pubtimeStr));
		goods.setAdminsId(adminsSess.getId());
		goods.setCreateTime(new Date());
		goods.setUpdateTime(new Date());
		resultJSON = this.goodsService.saveOneGoodsService(goods);
		return resultJSON.toJSONString(); 
	}
	
}
